using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 法力恢复Buff - 持续恢复法力值
/// </summary>
public class ManaRegenBuff : BuffBase
{
    private float m_TickInterval = 1.0f; // 每秒恢复一次
    private float m_LastTickTime;
    private long m_ManaPerTick;
    private float m_RegenMultiplier = 1.0f; // 恢复倍率

    public ManaRegenBuff(BuffData buffData, Entity caster, Entity target) : base(buffData, caster, target)
    {
        if (buffData is ManaRegenData manaData)
        {
            m_ManaPerTick = manaData.ManaPerTick;
            m_TickInterval = manaData.TickInterval;
            m_RegenMultiplier = manaData.RegenMultiplier;
        }
    }

    protected override void OnStart()
    {
        base.OnStart();
        m_LastTickTime = 0f;
        
        // 播放法力恢复特效
        if (BuffData.Effect != null)
        {
            var effect = GameObject.Instantiate(BuffData.Effect, Target.transform);
            effect.transform.localPosition = Vector3.zero;
        }
        
        Logger.Log("ManaRegenBuff", $"{Target.name} 开始法力恢复，每秒恢复 {m_ManaPerTick} 点法力值");
    }

    protected override void OnTick(float dt)
    {
        base.OnTick(dt);
        
        // 检查是否到了恢复法力值的时间
        if (Time.time - m_LastTickTime >= m_TickInterval)
        {
            ApplyManaRegeneration();
            m_LastTickTime = Time.time;
        }
    }

    private void ApplyManaRegeneration()
    {
        if (Target != null && !Target.HealthComponent.IsDead)
        {
            // 计算实际恢复量（考虑倍率）
            long actualMana = (long)(m_ManaPerTick * m_RegenMultiplier);
            
            // 恢复法力值（这里需要根据具体的法力系统实现）
            // if (Target.ManaComponent != null)
            // {
            //     Target.ManaComponent.RestoreMana(actualMana);
            // }
            
            Logger.Log("ManaRegenBuff", $"{Target.name} 恢复法力值 {actualMana}");
            
            // 触发法力恢复事件
            var args = ReferencePool.Acquire<EntityManaRestoreEventArgs>();
            args.Entity = Target;
            args.ManaAmount = actualMana;
            EventHelper.Fire(this, args);
        }
    }

    protected override void OnFinish()
    {
        base.OnFinish();
        Logger.Log("ManaRegenBuff", $"{Target.name} 法力恢复效果结束");
    }

    protected override void OnRemove()
    {
        base.OnRemove();
        // 清理特效
        var effects = Target.GetComponentsInChildren<ParticleSystem>();
        foreach (var effect in effects)
        {
            if (effect.name.Contains("ManaRegen"))
            {
                GameObject.Destroy(effect.gameObject);
            }
        }
    }

    public override bool IsCanMerge()
    {
        return true; // 法力恢复效果可以叠加，刷新持续时间
    }
}